package com.leyou.item.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.leyou.common.exception.pojo.ExceptionEnum;
import com.leyou.common.exception.pojo.LyException;
import com.leyou.common.pojo.PageResult;
import com.leyou.item.mapper.BrandMapper;
import com.leyou.item.pojo.Brand;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 品牌Service
 */
@Service
@Transactional
public class BrandService{
    @Autowired
    private BrandMapper brandMapper;

    public PageResult<Brand> brandPageQuery(Integer page, Integer rows, String key, String sortBy, Boolean desc) {
        //1.封装查询条件
        //1.1 IPage对象：封装分页参数
        //(查询前：IPage对象封装页面->后端数据)
        IPage<Brand> iPage = new Page(page,rows); // PageHelper.startPage(page,rows);

        //1.2 Wrapper：查询条件
        QueryWrapper<Brand> wrapper = Wrappers.query();

        //***把需要的条件封装进去QueryWrapper里面去***
        if(StringUtils.isNotEmpty(key)){
            /**
             * 参数一：查询的字段名称（不是属性名称）
             * 参数二：参数值
             */
            wrapper
                    .like("name",key)
                    .or()
                    .eq("letter",key.toUpperCase());
        }

        if(StringUtils.isNotEmpty(sortBy)){
           if(desc){
               //降序
               wrapper.orderByDesc(sortBy);
           }else{
               //升序
               //降序
               wrapper.orderByAsc(sortBy);
           }
        }


        //2.查询数据，获取结果
        //(查询后：IPage对象封装后端->前端数据)
        iPage = brandMapper.selectPage(iPage,wrapper);

        //3.处理(封装)结果
        //iPage.getTotal(): 总记录数
        //iPage.getPages()： 总页数
        //iPage.getRecords()： 数据列表
        PageResult<Brand> pageResult = new PageResult<Brand>(iPage.getTotal(),iPage.getPages(),iPage.getRecords());

        //4.返回结果
        return pageResult;
    }

    public void saveBrand(Brand brand, List<Long> cids) {
        try {
            //1.添加品牌数据
            brandMapper.insert(brand);//注意：MyBatis-Plus中insert方法会自动到数据库获取自增值赋值给对象的ID

            //2.添加分类品牌中间表数据
            brandMapper.saveCategoryAndBrand(cids,brand.getId());
        } catch (Exception e) {
            e.printStackTrace();
            throw new LyException(ExceptionEnum.INSERT_OPERATION_FAIL);
        }

    }

    public Brand findBrandById(Long id) {
        Brand brand = brandMapper.selectById(id);
        if(brand==null){
            throw new LyException(ExceptionEnum.BRAND_NOT_FOUND);
        }
        return brand;
    }

    public List<Brand> findBrandsByCid(Long id) {
        List<Brand> brands = brandMapper.findBrandsByCid(id);
        if(CollectionUtils.isEmpty(brands)){
            throw new LyException(ExceptionEnum.BRAND_NOT_FOUND);
        }
        return brands;
    }

    public List<Brand> findBrandsByIds(List<Long> ids) {
        List<Brand> brands = brandMapper.selectBatchIds(ids);
        if(CollectionUtils.isEmpty(brands)){
            throw new LyException(ExceptionEnum.BRAND_NOT_FOUND);
        }
        return brands;
    }
}
